/**
 * @description 弹出窗口脚本，处理用户界面交互
 * @author LingXiYi
 */

/**
 * @description 显示状态消息
 * @param {string} message - 要显示的消息
 * @param {string} type - 消息类型 ('success' | 'error')
 */
function showStatus(message, type = 'success') {
  const status = document.getElementById('status');
  status.textContent = message;
  status.className = `status ${type}`;
  
  setTimeout(() => {
    status.textContent = '';
    status.className = 'status';
  }, 3000);
}

document.addEventListener('DOMContentLoaded', async () => {
  const translationToggle = document.getElementById('translationToggle');
  const targetLanguage = document.getElementById('targetLanguage');
  
  // 加载保存的设置
  const { enabled, targetLang } = await chrome.storage.local.get(['enabled', 'targetLang']);
  translationToggle.checked = enabled || false;
  targetLanguage.value = targetLang || 'zh';
  
  // 监听开关变化
  translationToggle.addEventListener('change', async () => {
    const enabled = translationToggle.checked;
    const targetLang = targetLanguage.value;
    
    try {
      // 保存设置
      await chrome.storage.local.set({ enabled, targetLang });
      
      // 向content script发送消息
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      if (tab?.id) {
        await chrome.tabs.sendMessage(tab.id, {
          action: 'toggleTranslation',
          enabled,
          targetLang
        });
        
        showStatus(enabled ? '翻译已启用' : '翻译已关闭');
      }
    } catch (error) {
      console.error('设置更新失败:', error);
      showStatus('设置更新失败', 'error');
    }
  });
  
  // 监听语言选择变化
  targetLanguage.addEventListener('change', async () => {
    const enabled = translationToggle.checked;
    const targetLang = targetLanguage.value;
    
    try {
      // 保存设置
      await chrome.storage.local.set({ targetLang });
      
      // 如果翻译功能已启用，则重新触发翻译
      if (enabled) {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        if (tab?.id) {
          await chrome.tabs.sendMessage(tab.id, {
            action: 'toggleTranslation',
            enabled,
            targetLang
          });
          
          showStatus('语言已更新');
        }
      }
    } catch (error) {
      console.error('语言更新失败:', error);
      showStatus('语言更新失败', 'error');
    }
  });
}); 